package core

import (
	"blockchain/types"
	"bytes"
	"crypto/sha256"
	"encoding/gob"
)

type BlockHasher struct {
}

func (b BlockHasher) Encoding(block *Block) ([]byte, error) {
	return block.HeaderBytes(), nil
}

func (b BlockHasher) Decoding(block *Block, data []byte) error {
	buf := bytes.NewBuffer(data)
	dec := gob.NewDecoder(buf)
	err := dec.Decode(&block.Header)
	if err != nil {
		return err
	}

	return nil
}

func (b BlockHasher) Hash(block *Block) types.Hash {
	data, err := b.Encoding(block)
	if err != nil {
		panic(err)
	}

	return types.Hash(sha256.Sum256(data))
}
